import React, { Component } from 'react'

// 引入connect用于连接UI组件与redux
import {connect} from 'react-redux'
// 引入actionCreator，专门用于创建action对象
import {
  createIncrementAction, 
  createDecrementAction,
  createIncrementAsyncAction
} from '../../redux/count_action'

// Count UI组件
class Count extends Component {

  increment = () => {
    const {value} = this.selectNumber
    this.props.increment(value*1)
  }
  decrement = () => {
    const {value} = this.selectNumber
    this.props.decrement(value*1)
  }
  incrementIfOdd = () => {
    const {value} = this.selectNumber
    const count = this.props.count
    if(count % 2 !== 0) {
      this.props.increment(value*1)
    }
  }
  incrementAsync = () => {
    const {value} = this.selectNumber
    this.props.incrementAsync(value*1, 1000)
  }

  render() {
    return (
      <div>
        <h1>当前求和为：{this.props.count}</h1>
        <select ref={c => this.selectNumber = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>&nbsp;&nbsp;
        <button onClick={this.increment}>+</button>&nbsp;&nbsp;
        <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
        <button onClick={this.incrementIfOdd}>increment odd</button>&nbsp;&nbsp;
        <button onClick={this.incrementAsync}>increment async</button>
      </div>
    )
  }
}
/*
// 映射状态
const mapStateToProps = state => ({count: state})

// 映射操作状态的方法
const mapDispatchToProps = dispatch => ({
  // 通知redux执行方法
  increment: data => dispatch(createIncrementAction(data)),
  decrement: data => dispatch(createDecrementAction(data)),
  incrementAsync: (data, time) => dispatch(createIncrementAsyncAction(data, time))
})
*/

// 使用connect()()创建并暴露一个Count的容器组件
// export default connect(mapStateToProps, mapDispatchToProps)(CountUI)
export default connect(
  state => ({count: state}),
  // mapDispatchToProps的简写
  {
    increment: createIncrementAction,
    decrement: createDecrementAction,
    incrementAsync: createIncrementAsyncAction
  }
)(Count)
